package cn.shujuhai.qtadmin.platform.kit;

import java.util.Objects;

import org.jetbrains.annotations.Nullable;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Describe: Security 工 具 类
 * 
 * @author dch CreateTime: 2019/10/23
 */
public class SecurityUtil {

    private SecurityUtil() {

    }

    /**
     * 获取当前登录用户的信息 return Authentication 权鉴对象
     */
    public static @Nullable Authentication currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return authentication;
        }
        return null;
    }

    /**
     * 验证当前用户是否登录
     * 
     * @return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }

    /**
     * 获取当前登录用户对象 retrun SysUser
     */
    public static Object currentUserObj() {
        return Objects.requireNonNull(SecurityUtil.currentUser()).getPrincipal();
    }

}
